package dao;

import pojo.User;

import java.sql.*;

public class DBconnection {
    //新版驱动名字为 driverClass=“com.mysql.cj.jdbc.Driver”
    private static final String JDBC_Driver = "com.mysql.cj.jdbc.Driver";//jdbc驱动名称
    private static final String DB_Url = "jdbc:mysql://localhost:3306/newdb?serverTimezone=UTC";//数据库url
    private static final String DB_User = "root";//数据库的用户名
    private static final String DB_Password = "mysql@123";//数据库的密码

    private static void MysqlConnection(){
        Connection connection = null;
        Statement statement = null;

        try{
            //1- 注册JDBC驱动
            Class.forName(JDBC_Driver);

            //2- 连接数据库
            System.out.println("开始连接数据库...");
            connection = DriverManager.getConnection(DB_Url,DB_User,DB_Password);

            //3- 执行查询
            System.out.println("开始实例化Stetement对象...");
            statement = connection.createStatement();
            String sql = "SELECT * FROM user";//查询语句
            String sql2="INSERT INTO user values(null,'hjq','123456789')";
            statement.executeUpdate(sql2);
            ResultSet rs = statement.executeQuery(sql);//执行查询语句

            //4- 展开结果集数据库
            while (rs.next()){
                int id = rs.getInt("userID");
                String name = rs.getString("username");
                String password=rs.getString("password");

                System.out.println(new User(id,name,password));

            }

            //5- 关闭连接
            rs.close();
            statement.close();
            connection.close();


        }catch(SQLException se){
            se.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(statement != null) statement.close();
            }catch (SQLException se2){

            }
            try{
                if(connection != null) connection.close();
            }catch (SQLException se3){
                se3.printStackTrace();
            }
        }
    }
    public static void main(String[] args){
        MysqlConnection();
    }
}



